1   /*
2    * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
3    *
4    * Redistribution and use in source and binary forms, with or without
5    * modification, are permitted provided that the following conditions
6    * are met:
7    *
8    *   - Redistributions of source code must retain the above copyright
9    *     notice, this list of conditions and the following disclaimer.
10   *
11   *   - Redistributions in binary form must reproduce the above copyright
12   *     notice, this list of conditions and the following disclaimer in the
13   *     documentation and/or other materials provided with the distribution.
14   *
15   *   - Neither the name of Oracle nor the names of its
16   *     contributors may be used to endorse or promote products derived
17   *     from this software without specific prior written permission.
18   *
19   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20   * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21   * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22   * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24   * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25   * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26   * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27   * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28   * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30   */
31  
32  
33  import java.awt.Color;
34  import java.awt.Dimension;
35  import java.awt.Graphics;
36  import java.awt.event.MouseEvent;
37  import java.awt.event.MouseListener;
38  
39  
40  /**
41   * A simple applet class to demonstrate a sort algorithm.
42   * You can specify a sorting algorithm using the "alg"
43   * attribute. When you click on the applet, a thread is
44   * forked which animates the sorting algorithm.
45   *
46   * @author James Gosling
47   */
48  @SuppressWarnings("serial")
49  public class SortItem extends java.applet.Applet implements Runnable,
50          MouseListener {
51  
52      /**
53       * The thread that is sorting (or null).
54       */
55      private Thread kicker;
56      /**
57       * The array that is being sorted.
58       */
59      int arr[];
60      /**
61       * The high water mark.
62       */
63      int h1 = -1;
64      /**
65       * The low water mark.
66       */
67      int h2 = -1;
68      /**
69       * The name of the algorithm.
70       */
71      String algName;
72      /**
73       * The sorting algorithm (or null).
74       */
75      SortAlgorithm algorithm;
76      Dimension initialSize = null;
77  
78      /**
79       * Fill the array with random numbers from 0..n-1.
80       */
81      void scramble() {
82          initialSize = getSize();
83          int a[] = new int[initialSize.height / 2];
84          double f = initialSize.width / (double) a.length;
85  
86          for (int i = a.length; --i >= 0;) {
87              a[i] = (int) (i * f);
88          }
89          for (int i = a.length; --i >= 0;) {
90              int j = (int) (i * Math.random());
91              int t = a[i];
92              a[i] = a[j];
93              a[j] = t;
94          }
95          arr = a;
96      }
97  
98      /**
99       * Pause a while.
100      * @see SortAlgorithm
101      */
102     void pause() {
103         pause(-1, -1);
104     }
105 
106     /**
107      * Pause a while, and draw the high water mark.
108      * @see SortAlgorithm
109      */
110     void pause(int H1) {
111         pause(H1, -1);
112     }
113 
114     /**
115      * Pause a while, and draw the low&high water marks.
116      * @see SortAlgorithm
117      */
118     void pause(int H1, int H2) {
119         h1 = H1;
120         h2 = H2;
121         if (kicker != null) {
122             repaint();
123         }
124         try {
125             Thread.sleep(20);
126         } catch (InterruptedException e) {
127         }
128     }
129 
130     /**
131      * Initialize the applet.
132      */
133     @Override
134     public void init() {
135         String at = getParameter("alg");
136         if (at == null) {
137             at = "BubbleSort";
138         }
139 
140         algName = at + "Algorithm";
141         scramble();
142 
143         resize(100, 100);
144         addMouseListener(this);
145     }
146 
147     @Override
148     public void start() {
149         h1 = h2 = -1;
150         scramble();
151         repaint();
152         showStatus(getParameter("alg"));
153     }
154 
155     /**
156      * Deallocate resources of applet.
157      */
158     @Override
159     public void destroy() {
160         removeMouseListener(this);
161     }
162 
163     /**
164      * Paint the array of numbers as a list
165      * of horizontal lines of varying lengths.
166      */
167     @Override
168     public void paint(Graphics g) {
169         int a[] = arr;
170         int y = 0;
171         int deltaY = 0, deltaX = 0, evenY = 0;
172 
173         Dimension currentSize = getSize();
174         int currentHeight = currentSize.height;
175         int currentWidth = currentSize.width;
176 
177         // Check to see if the applet has been resized since it
178         // started running.  If so, need the deltas to make sure
179         // the applet is centered in its containing panel.
180         // The evenX and evenY are because the high and low
181         // watermarks are calculated from the top, but the rest
182         // of the lines are calculated from the bottom, which
183         // can lead to a discrepancy if the window is not an
184         // even size.
185         if (!currentSize.equals(initialSize)) {
186             evenY = (currentHeight - initialSize.height) % 2;
187             deltaY = (currentHeight - initialSize.height) / 2;
188             deltaX = (currentWidth - initialSize.width) / 2;
189 
190             if (deltaY < 0) {
191                 deltaY = 0;
192                 evenY = 0;
193             }
194             if (deltaX < 0) {
195                 deltaX = 0;
196             }
197         }
198 
199         // Erase old lines
200         g.setColor(getBackground());
201         y = currentHeight - deltaY - 1;
202         for (int i = a.length; --i >= 0; y -= 2) {
203             g.drawLine(deltaX + arr[i], y, currentWidth, y);
204         }
205 
206         // Draw new lines
207         g.setColor(Color.black);
208         y = currentHeight - deltaY - 1;
209         for (int i = a.length; --i >= 0; y -= 2) {
210             g.drawLine(deltaX, y, deltaX + arr[i], y);
211         }
212 
213         if (h1 >= 0) {
214             g.setColor(Color.red);
215             y = deltaY + evenY + h1 * 2 + 1;
216             g.drawLine(deltaX, y, deltaX + initialSize.width, y);
217         }
218         if (h2 >= 0) {
219             g.setColor(Color.blue);
220             y = deltaY + evenY + h2 * 2 + 1;
221             g.drawLine(deltaX, y, deltaX + initialSize.width, y);
222         }
223     }
224 
225     /**
226      * Update without erasing the background.
227      */
228     @Override
229     public void update(Graphics g) {
230         paint(g);
231     }
232 
233     /**
234      * Run the sorting algorithm. This method is
235      * called by class Thread once the sorting algorithm
236      * is started.
237      * @see java.lang.Thread#run
238      * @see SortItem#mouseUp
239      */
240     @Override
241     public void run() {
242         try {
243             if (algorithm == null) {
244                 algorithm = (SortAlgorithm) Class.forName(algName).newInstance();
245                 algorithm.setParent(this);
246             }
247             algorithm.init();
248             algorithm.sort(arr);
249         } catch (Exception e) {
250         }
251     }
252 
253     /**
254      * Stop the applet. Kill any sorting algorithm that
255      * is still sorting.
256      */
257     @Override
258     public synchronized void stop() {
259         if (algorithm != null) {
260             try {
261                 algorithm.stop();
262             } catch (IllegalThreadStateException e) {
263                 // ignore this exception
264             }
265             kicker = null;
266         }
267     }
268 
269     /**
270      * For a Thread to actually do the sorting. This routine makes
271      * sure we do not simultaneously start several sorts if the user
272      * repeatedly clicks on the sort item.  It needs to be
273      * synchronized with the stop() method because they both
274      * manipulate the common kicker variable.
275      */
276     private synchronized void startSort() {
277         if (kicker == null || !kicker.isAlive()) {
278             kicker = new Thread(this);
279             kicker.start();
280         }
281     }
282 
283     @Override
284     public void mouseClicked(MouseEvent e) {
285         showStatus(getParameter("alg"));
286     }
287 
288     @Override
289     public void mousePressed(MouseEvent e) {
290     }
291 
292     /**
293      * The user clicked in the applet. Start the clock!
294      */
295     @Override
296     public void mouseReleased(MouseEvent e) {
297         startSort();
298         e.consume();
299     }
300 
301     @Override
302     public void mouseEntered(MouseEvent e) {
303     }
304 
305     @Override
306     public void mouseExited(MouseEvent e) {
307     }
308 
309     @Override
310     public String getAppletInfo() {
311         return "Title: SortDemo \nAuthor: James Gosling 1.17f, 10 Apr 1995 \nA simple applet class to demonstrate a sort algorithm.  \nYou can specify a sorting algorithm using the 'alg' attribute.  \nWhen you click on the applet, a thread is forked which animates \nthe sorting algorithm.";
312     }
313 
314     @Override
315     public String[][] getParameterInfo() {
316         String[][] info = {
317             { "alg", "string",
318                 "The name of the algorithm to run.  You can choose from the provided algorithms or suppply your own, as long as the classes are runnable as threads and their names end in 'Algorithm.'  BubbleSort is the default.  Example:  Use 'QSort' to run the QSortAlgorithm class." }
319         };
320         return info;
321     }
322 }